package models;

import play.data.validation.Constraints;
import play.db.ebean.Model;

import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Entity
public class Category extends Model {

    @Id
    public Long id;

    @Constraints.Required
    public String name;

    @Constraints.Required
    public ERowType type;

    public static Model.Finder<Long, Category> find = new Model.Finder<Long, Category>(Long.class, Category.class);

    public static List<Category> findByType(ERowType type) {
        List<Category> categories;
        if (type != null) {
            categories = Category.find.where().eq("type", type).orderBy("name").findList();
        } else {
            categories = Category.find.where().orderBy("name").findList();
        }
        return categories;
    }

    public static Map<String, String> options(ERowType type) {
        LinkedHashMap<String, String> options = new LinkedHashMap<String, String>();
        List<Category> categories = Category.findByType(type);
        for (Category category : categories) {
            options.put(category.id.toString(), category.name);
        }
        return options;
    }

    public float monthSum(int year, int month){
        List<AccountingRow> accountingRows = AccountingRow.month(year, month, this);
        float sum = 0F;
        for(AccountingRow accountingRow : accountingRows){
            sum += accountingRow.amount;
        }
        return sum;
    }

    public float fromJanuarySum(int year, int month){
        List<AccountingRow> accountingRows = AccountingRow.fromJanuary(year, month, this);
        float sum = 0F;
        for(AccountingRow accountingRow : accountingRows){
            sum += accountingRow.amount;
        }
        return sum;
    }
}
